package com.ilxqx.framework.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * Redis工具类
 * @author venus
 */
@Component
@SuppressWarnings("unchecked")
public final class RedisUtils {

    private static RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisUtils(@Qualifier("frameworkRedisTemplate") RedisTemplate<String, Object> redisTemplate) {
        RedisUtils.redisTemplate = redisTemplate;
    }

    /**
     * 设置一个值
     * @param key 键
     * @param value 值
     * @param duration 存活时间
     */
    public static void set(String key, Object value, Duration duration) {
        RedisUtils.redisTemplate.opsForValue().set(key, value, duration);
    }

    /**
     * 获取一个值
     * @param key 键
     * @param <T> 泛型
     * @return 值
     */
    public static <T> T get(String key) {
        Object value = RedisUtils.redisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }
        return (T) value;
    }

    /**
     * 删除一个键
     * @param key 键
     */
    public static void remove(String key) {
        RedisUtils.redisTemplate.delete(key);
    }

}
